import { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Space,
  Card,
  Tag,
  Input,
  Select,
  Modal,
  message,
  Dropdown,
  Row,
  Col,
  Statistic,
  DatePicker,
  Descriptions
} from 'antd';
import {
  EditOutlined,
  DeleteOutlined,
  MoreOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  CloseCircleOutlined,
  EyeOutlined,
} from '@ant-design/icons';
import useOrdersStore from '../../store/orders/useOrdersStore';
import OrderForm from './OrderForm';
import dayjs from 'dayjs';

const { Search } = Input;
const { Option } = Select;
const { RangePicker } = DatePicker;

const orderStatuses = [
  { value: 'completed', label: '已完成', color: 'success', icon: <CheckCircleOutlined /> },
  { value: 'pending', label: '待支付', color: 'warning', icon: <ClockCircleOutlined /> },
  { value: 'cancelled', label: '已取消', color: 'error', icon: <CloseCircleOutlined /> }
];

const OrdersList = () => {
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [currentOrder, setCurrentOrder] = useState(null);
  const [searchOrderNumber, setSearchOrderNumber] = useState('');
  const [searchMemberId, setSearchMemberId] = useState('');
  
  const {
    orders,
    loading,
    filters,
    getOrders,
    deleteOrder,
    updateOrderStatus,
  } = useOrdersStore();

  useEffect(() => {
    getOrders(filters);
  }, []);

  const statusesByValue = orderStatuses.reduce((acc, status) => {
    acc[status.value] = status;
    return acc;
  }, {});

  const statistics = {
    total: orders.length,
    totalSales: orders.filter(o => o.status === 'completed').reduce((sum, order) => sum + order.amount, 0),
    completedCount: orders.filter(o => o.status === 'completed').length,
    pendingCount: orders.filter(o => o.status === 'pending').length,
    cancelledCount: orders.filter(o => o.status === 'cancelled').length,
  };

  const columns = [
    {
      title: '订单号',
      dataIndex: 'orderNumber',
      key: 'orderNumber',
      width: 180,
      render: (orderNumber) => (
        <span style={{ fontWeight: 500, color: '#1890ff' }}>{orderNumber}</span>
      ),
    },
    {
      title: '桌号',
      dataIndex: 'tableNumber',
      key: 'tableNumber',
      width: 100,
      render: (tableNumber) => (
        <Tag color="cyan" style={{ fontWeight: 500 }}>{tableNumber}</Tag>
      ),
    },
    {
      title: '会员信息',
      key: 'member',
      width: 200,
      render: (_, record) => (
        <Space direction="vertical" size={0}>
          <span style={{ fontWeight: 500 }}>{record.memberName}</span>
          <span style={{ fontSize: 12, color: '#999' }}>{record.memberPhone}</span>
        </Space>
      ),
    },
    {
      title: '订单金额',
      key: 'amount',
      width: 180,
      render: (_, record) => (
        <Space direction="vertical" size={0}>
          <span style={{ fontWeight: 600, color: '#3f8600' }}>¥{record.amount.toFixed(2)}</span>
          {record.discount < 100 && (
            <span style={{ fontSize: 12, color: '#999' }}>
              原价: ¥{record.originalAmount.toFixed(2)} ({record.discount}折)
            </span>
          )}
        </Space>
      ),
    },
    {
      title: '订单状态',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (status) => {
        const config = statusesByValue[status];
        return (
          <Tag color={config.color} icon={config.icon}>
            {config.label}
          </Tag>
        );
      },
    },
    {
      title: '下单时间',
      dataIndex: 'orderTime',
      key: 'orderTime',
      width: 180,
      render: (time) => dayjs(time).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '完成时间',
      dataIndex: 'completedTime',
      key: 'completedTime',
      width: 180,
      render: (time) => time ? dayjs(time).format('YYYY-MM-DD HH:mm') : '-',
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 120,
      render: (_, record) => {
        const items = [
          {
            key: 'detail',
            label: '查看详情',
            icon: <EyeOutlined />,
            onClick: () => handleViewDetail(record),
          },
          {
            key: 'edit',
            label: '编辑订单',
            icon: <EditOutlined />,
            onClick: () => handleEdit(record),
          },
          {
            type: 'divider',
          },
        ];

        if (record.status === 'pending') {
          items.push({
            key: 'complete',
            label: '标记已完成',
            icon: <CheckCircleOutlined />,
            onClick: () => handleStatusChange(record.id, 'completed'),
          });
          items.push({
            key: 'cancel',
            label: '取消订单',
            icon: <CloseCircleOutlined />,
            onClick: () => handleStatusChange(record.id, 'cancelled'),
          });
        } else if (record.status === 'cancelled') {
          items.push({
            key: 'pending',
            label: '恢复待支付',
            icon: <ClockCircleOutlined />,
            onClick: () => handleStatusChange(record.id, 'pending'),
          });
        }

        items.push(
          { type: 'divider' },
          {
            key: 'delete',
            label: '删除订单',
            icon: <DeleteOutlined />,
            danger: true,
            onClick: () => handleDelete(record),
          }
        );

        return (
          <Dropdown
            menu={{ items }}
            trigger={['click']}
          >
            <Button type="text" icon={<MoreOutlined />} />
          </Dropdown>
        );
      },
    },
  ];

  const handleViewDetail = (record) => {
    setCurrentOrder(record);
    setDetailModalVisible(true);
  };

  const handleEdit = (record) => {
    setCurrentOrder(record);
    setEditModalVisible(true);
  };

  const handleDelete = (record) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除订单 "${record.orderNumber}" 吗？此操作不可恢复。`,
      okText: '确认',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        try {
          await deleteOrder(record.id);
          message.success('删除成功');
        } catch {
          message.error('删除失败');
        }
      },
    });
  };

  const handleStatusChange = async (id, status) => {
    try {
      await updateOrderStatus(id, status);
      message.success('订单状态更新成功');
    } catch {
      message.error('状态更新失败');
    }
  };

  const handleStatusFilter = (status) => {
    getOrders({ ...filters, status });
  };

  const handleSearchOrderNumber = (value) => {
    setSearchOrderNumber(value);
    getOrders({ ...filters, orderNumber: value });
  };

  const handleSearchMemberId = (value) => {
    setSearchMemberId(value);
    getOrders({ ...filters, memberId: value });
  };

  const handleDateRangeChange = (dates) => {
    if (dates && dates.length === 2) {
      getOrders({ 
        ...filters, 
        dateRange: [
          dates[0].format('YYYY-MM-DD 00:00:00'),
          dates[1].format('YYYY-MM-DD 23:59:59')
        ]
      });
    } else {
      getOrders({ ...filters, dateRange: null });
    }
  };

  return (
    <div className="p-6">
      <Row gutter={16} className="mb-6">
        <Col span={12}>
          <Card>
            <Statistic
              title="总订单数"
              value={statistics.total}
            />
          </Card>
        </Col>
        <Col span={12}>
          <Card>
            <Statistic
              title="总销售金额"
              value={statistics.totalSales}
              precision={2}
              prefix="¥"
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
      </Row>

      <Card>
        <div style={{ marginBottom: 24 }}>
          <Space size={12} wrap>
            <Select
              value={filters.status}
              style={{ width: 140 }}
              onChange={handleStatusFilter}
            >
              <Option value="all">全部状态</Option>
              {orderStatuses.map(status => (
                <Option key={status.value} value={status.value}>{status.label}</Option>
              ))}
            </Select>
            <Search
              placeholder="搜索订单号"
              allowClear
              onSearch={handleSearchOrderNumber}
              style={{ width: 200 }}
            />
            <Search
              placeholder="搜索会员号/手机号"
              allowClear
              onSearch={handleSearchMemberId}
              style={{ width: 200 }}
            />
            <RangePicker
              placeholder={['开始日期', '结束日期']}
              onChange={handleDateRangeChange}
              style={{ width: 280 }}
            />
          </Space>
        </div>

        <Table
          columns={columns}
          dataSource={orders}
          rowKey="id"
          loading={loading}
          pagination={{
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条`,
            defaultPageSize: 10,
          }}
          scroll={{ x: 1200 }}
        />
      </Card>

      <Modal
        title="订单详情"
        open={detailModalVisible}
        onCancel={() => {
          setDetailModalVisible(false);
          setCurrentOrder(null);
        }}
        footer={null}
        width={800}
        destroyOnClose
      >
        {currentOrder && (
          <div>
            <Descriptions bordered column={2}>
              <Descriptions.Item label="订单号">{currentOrder.orderNumber}</Descriptions.Item>
              <Descriptions.Item label="桌号">
                <Tag color="cyan">{currentOrder.tableNumber}</Tag>
              </Descriptions.Item>
              <Descriptions.Item label="会员姓名">{currentOrder.memberName}</Descriptions.Item>
              <Descriptions.Item label="手机号">{currentOrder.memberPhone}</Descriptions.Item>
              <Descriptions.Item label="下单时间">
                {dayjs(currentOrder.orderTime).format('YYYY-MM-DD HH:mm')}
              </Descriptions.Item>
              <Descriptions.Item label="完成时间">
                {currentOrder.completedTime ? dayjs(currentOrder.completedTime).format('YYYY-MM-DD HH:mm') : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="订单状态">
                <Tag color={statusesByValue[currentOrder.status].color} icon={statusesByValue[currentOrder.status].icon}>
                  {statusesByValue[currentOrder.status].label}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="折扣">
                {currentOrder.discount}折
              </Descriptions.Item>
            </Descriptions>

            <div style={{ marginTop: 24 }}>
              <h3>订单明细</h3>
              <Table
                dataSource={currentOrder.items}
                pagination={false}
                rowKey={(_, index) => index}
                columns={[
                  {
                    title: '菜品名称',
                    dataIndex: 'dishName',
                    key: 'dishName',
                  },
                  {
                    title: '规格',
                    dataIndex: 'size',
                    key: 'size',
                  },
                  {
                    title: '数量',
                    dataIndex: 'quantity',
                    key: 'quantity',
                  },
                  {
                    title: '单价',
                    dataIndex: 'price',
                    key: 'price',
                    render: (price) => `¥${price.toFixed(2)}`,
                  },
                  {
                    title: '折扣',
                    dataIndex: 'discount',
                    key: 'discount',
                    render: (discount) => `${discount}%`,
                  },
                  {
                    title: '小计',
                    key: 'subtotal',
                    render: (_, record) => (
                      <span style={{ fontWeight: 500 }}>
                        ¥{(record.price * record.quantity * record.discount / 100).toFixed(2)}
                      </span>
                    ),
                  },
                ]}
              />
            </div>

            <div style={{ marginTop: 16, textAlign: 'right' }}>
              {currentOrder.discount < 100 && (
                <div style={{ marginBottom: 8 }}>
                  <span>原价: </span>
                  <span style={{ fontSize: 16, textDecoration: 'line-through', color: '#999' }}>
                    ¥{currentOrder.originalAmount.toFixed(2)}
                  </span>
                </div>
              )}
              <div>
                <span style={{ fontSize: 16 }}>实付金额: </span>
                <span style={{ fontSize: 24, fontWeight: 600, color: '#3f8600' }}>
                  ¥{currentOrder.amount.toFixed(2)}
                </span>
              </div>
            </div>
          </div>
        )}
      </Modal>

      <Modal
        title="编辑订单"
        open={editModalVisible}
        onCancel={() => {
          setEditModalVisible(false);
          setCurrentOrder(null);
        }}
        footer={null}
        width={700}
        destroyOnClose
      >
        <OrderForm
          order={currentOrder}
          onSuccess={() => {
            setEditModalVisible(false);
            setCurrentOrder(null);
            getOrders(filters);
          }}
          onCancel={() => {
            setEditModalVisible(false);
            setCurrentOrder(null);
          }}
        />
      </Modal>
    </div>
  );
};

export default OrdersList;
